package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.dto.RoleInfo;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public List<String> roleNameList(String role_id) {
        String[] strings = role_id.split(",");
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId, strings);
        List<Role> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    @Override
    public void removeWithMenu(String id) {
       LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
       lqw.eq(User::getId,"[\"" + id + "\"]");
       if(userService.count(lqw)!=0){
           throw new BusinessException("该角色有人,不能删除");
       }
       this.removeById(id);
       LambdaQueryWrapper<RoleMenu> lqw1=new LambdaQueryWrapper<>();
       lqw1.eq(RoleMenu::getRoleId,id);
       roleMenuService.remove(lqw1);
    }


//    @Override
//    public void updateWithMenu(RoleInfo roleInfo) {
//       //跟心role表基本信息
//        this.updateById(roleInfo);
//        //清理当前角色对应权限
//        LambdaQueryWrapper<RoleMenu> lqw=new LambdaQueryWrapper<>();
//        lqw.eq(RoleMenu::getRoleId,roleInfo.getId());
//        //id一致
//        roleMenuService.remove(lqw);
//        //添加当前提交过来的权限数据
//        ArrayList<String> menuids = roleInfo.getMenuids();
//        for (String menuid : menuids) {
//            RoleMenu sysRoleMenu = new RoleMenu();
//            sysRoleMenu.setRoleId(roleInfo.getId());
//            sysRoleMenu.setMenuId(menuid);
//            roleMenuService.save(sysRoleMenu);
//        }
//    }
}
